﻿from PySide6.QtCore import QDateTime, Slot, Qt
from PySide6.QtWidgets import QMessageBox, QDialog, QTableWidgetItem
from PySide6.QtGui import QIcon, QColor
from Devices.DeviceWindow import DeviceWindow
from Devices.Chiot.Bulb.Forms.TimerSetWindow import TimerSetWindow
from Devices.Chiot.Bulb.DeviceBulb import DeviceBulb
from Devices.Chiot.Bulb.BulbParser import BulbParser

from Devices.Chiot.Bulb.Forms.BulbWindow_UI import Ui_FormBulbWindow

class BulbWindow(DeviceWindow):
    def __init__(self, supportDevice, parent = None):
        super().__init__(supportDevice, parent)

        self.__ui = Ui_FormBulbWindow()
        self.__ui.setupUi(self)
        self.SetupUi(self.__ui)

        self.__TimerSetWindow = TimerSetWindow()
        self.__Timers = []
        self.__DeviceFullStatus = DeviceBulb.DeviceFullStatus()

        self._HttpServerWindow.SetLogServerEnable(False)
        self._OtaUrl = self.__ui.lineEdit_downloadUrl.text()

        self.__ui.tabWidget.setCurrentIndex(0)
        self.__ui.dateTimeEdit_DelayTime.setDateTime(QDateTime.currentDateTime())
        self.__ui.progressBar_Ota.setVisible(False)

    def Connect(self, cmdPort, logPort):
        super().Connect(cmdPort, logPort)
        self.__ui.lineEdit_downloadUrl.setText(self._OtaUrl % (self._HttpServerWindow.GetIP(), self._HttpServerWindow.GetPort(), self._SupportDevice.deviceBinName))

    def Connected(self, ip, port):
        cmd = BulbParser.PackGetFullStatus()
        self.SendCommandText(cmd)

    def SetLightAttrUI(self, fullStatus):
        #禁用信号，避免重复发送
        self.__ui.horizontalSlider_rgbBrightness.blockSignals(True)
        self.__ui.horizontalSlider_Saturation.blockSignals(True)
        self.__ui.horizontalSlider_Red.blockSignals(True)
        self.__ui.horizontalSlider_Green.blockSignals(True)
        self.__ui.horizontalSlider_Blue.blockSignals(True)
        self.__ui.horizontalSlider_whiteBrightness.blockSignals(True)
        self.__ui.horizontalSlider_Temprature.blockSignals(True)

        #灯光设置
        self.__ui.horizontalSlider_rgbBrightness.setValue(fullStatus.lightAttr.rgb.rgbBrightness)
        self.__ui.horizontalSlider_Saturation.setValue(fullStatus.lightAttr.rgb.saturation)
        self.__ui.horizontalSlider_Red.setValue(fullStatus.lightAttr.rgb.red)
        self.__ui.horizontalSlider_Green.setValue(fullStatus.lightAttr.rgb.green)
        self.__ui.horizontalSlider_Blue.setValue(fullStatus.lightAttr.rgb.blue)
        self.__ui.horizontalSlider_whiteBrightness.setValue(fullStatus.lightAttr.white.whiteBrightness)
        self.__ui.horizontalSlider_Temprature.setValue(fullStatus.lightAttr.white.temprature)

        self.__ui.label_rgbBrightness.setText(str(fullStatus.lightAttr.rgb.rgbBrightness))
        self.__ui.label_Saturation.setText(str(fullStatus.lightAttr.rgb.saturation))
        self.__ui.label_Red.setText(str(fullStatus.lightAttr.rgb.red))
        self.__ui.label_Green.setText(str(fullStatus.lightAttr.rgb.green))
        self.__ui.label_Blue.setText(str(fullStatus.lightAttr.rgb.blue))
        self.__ui.label_whiteBrightness.setText(str(fullStatus.lightAttr.white.whiteBrightness))
        self.__ui.label_Temprature.setText(str(fullStatus.lightAttr.white.temprature))

        #启用信号
        self.__ui.horizontalSlider_rgbBrightness.blockSignals(False)
        self.__ui.horizontalSlider_Saturation.blockSignals(False)
        self.__ui.horizontalSlider_Red.blockSignals(False)
        self.__ui.horizontalSlider_Green.blockSignals(False)
        self.__ui.horizontalSlider_Blue.blockSignals(False)
        self.__ui.horizontalSlider_whiteBrightness.blockSignals(False)
        self.__ui.horizontalSlider_Temprature.blockSignals(False)

    def SetDeviceFullStatus(self, msgValue):
        if BulbParser.ParseFullStatus(msgValue, self.__DeviceFullStatus):
            #基本信息
            self.__ui.label_Mac.setText(self.__DeviceFullStatus.mac)
            self.__ui.label_firmwareVersion.setText(self.__DeviceFullStatus.firmwareVersion)
            self.__ui.label_hardwareVersion.setText(self.__DeviceFullStatus.hardwareVersion)
            self.__ui.label_modelId.setText(self.__DeviceFullStatus.modelId)
            self.__ui.label_protocol.setText(self.__DeviceFullStatus.protocol)
            self.SetPowerType(self.__DeviceFullStatus.powerType)
            self.SetLedDriver(self.__DeviceFullStatus.ledDriver)
            self.SetCloudType(self.__DeviceFullStatus.cloudType)
            self.SetInterfaceType(self.__DeviceFullStatus.interfaceType)
            self.SetGradientTime(self.__DeviceFullStatus.gradientTime)
            
            self.__ui.label_buildTime.setText(self.__DeviceFullStatus.buildTime)
            self.__ui.label_heartbeatFreq.setText("%d秒" % (self.__DeviceFullStatus.heartbeatFreq))
            self.__ui.label_timezone.setText(self.__DeviceFullStatus.timezone)

            #模式设置
            self.__ui.checkBox_switch.setChecked(self.__DeviceFullStatus.switch_state)
            self.__ui.checkBox_noDisturb.setChecked(self.__DeviceFullStatus.noDisturb)

            if self.__DeviceFullStatus.lightAttr.lightMode == DeviceBulb.LightMode.LIGHT_RGB:
                self.__ui.label_CurrLightMode.setText("彩光")
                self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:rgb(255, 0, 255);")
                self.__ui.groupBox_RGB.setEnabled(True)
                self.__ui.groupBox_White.setEnabled(False)
                self.__ui.groupBox_Atmosphere.setEnabled(False)
            elif self.__DeviceFullStatus.lightAttr.lightMode == DeviceBulb.LightMode.LIGHT_WHITE:
                self.__ui.label_CurrLightMode.setText("白光")
                self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:black;")
                self.__ui.groupBox_RGB.setEnabled(False)
                self.__ui.groupBox_White.setEnabled(True)
                self.__ui.groupBox_Atmosphere.setEnabled(False)
            else:
                self.__ui.label_CurrLightMode.setText("氛围")
                self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
                self.__ui.groupBox_RGB.setEnabled(False)
                self.__ui.groupBox_White.setEnabled(False)
                self.__ui.groupBox_Atmosphere.setEnabled(True)

            #灯光设置
            self.SetLightAttrUI(self.__DeviceFullStatus)

            #氛围设置
            self.__ui.lineEdit_AtmosphereID.setText(str(self.__DeviceFullStatus.atmosphereAttr.id));
            self.__ui.plainTextEdit_AtmosphereScript.setPlainText(self.__DeviceFullStatus.atmosphereAttr.script);

            #定时器
            self.__ui.tableWidget_Timers.setRowCount(0)
            self.__Timers.clear()
            for i in range(len(self.__DeviceFullStatus.timers)):
                self.SetTimerToList(self.__DeviceFullStatus.timers[i])

            #倒计时
            if 0 != self.__DeviceFullStatus.delay.end:
                self.__ui.lineEdit_DelayID.setPlaceholderText("");
                self.__ui.lineEdit_DelayID.setText(self.__DeviceFullStatus.delay.id)
                self.__ui.checkBox_DelayEnable.setChecked(self.__DeviceFullStatus.delay.enable)
                self.__ui.dateTimeEdit_DelayTime.setDateTime(QDateTime.fromSecsSinceEpoch(self.__DeviceFullStatus.delay.end))
                
                #倒计时的灯光模式
                for i in range(len(self.__DeviceFullStatus.delay.services)):
                    if "switch" == self.__DeviceFullStatus.delay.services[i].serviceId:
                        self.__ui.checkBox_DelaySwitch.setChecked(1 == self.__DeviceFullStatus.delay.services[i].paraValue)
                    elif "lightMode" == self.__DeviceFullStatus.delay.services[i].serviceId:
                        self.__ui.comboBox_DelayLightMode.setCurrentIndex(self.__DeviceFullStatus.delay.services[i].paraValue)
                    elif "rgbBrightness" == self.__DeviceFullStatus.delay.services[i].serviceId:
                        self.__ui.horizontalSlider_Delay_rgbBrightness.setValue(self.__DeviceFullStatus.delay.services[i].paraValue)
                    elif "saturation" == self.__DeviceFullStatus.delay.services[i].serviceId:
                        self.__ui.horizontalSlider_Delay_Saturation.setValue(self.__DeviceFullStatus.delay.services[i].paraValue)
                    elif "colour" == self.__DeviceFullStatus.delay.services[i].serviceId:
                        if "red" == self.__DeviceFullStatus.delay.services[i].para:
                            self.__ui.horizontalSlider_Delay_Red.setValue(self.__DeviceFullStatus.delay.services[i].paraValue)
                        elif "green" == self.__DeviceFullStatus.delay.services[i].para:
                            self.__ui.horizontalSlider_Delay_Green.setValue(self.__DeviceFullStatus.delay.services[i].paraValue)
                        else:
                            self.__ui.horizontalSlider_Delay_Blue.setValue(self.__DeviceFullStatus.delay.services[i].paraValue)
                    elif "whiteBrightness" == self.__DeviceFullStatus.delay.services[i].serviceId:
                        self.__ui.horizontalSlider_Delay_whiteBrightness.setValue(self.__DeviceFullStatus.delay.services[i].paraValue)
                    elif "colorTemperature" == self.__DeviceFullStatus.delay.services[i].serviceId:
                        self.__ui.horizontalSlider_Delay_Temprature.setValue(BulbParser.TemperatureRate(self.__DeviceFullStatus.delay.services[i].paraValue))
                    else:
                        self.ShowMessageBox("同步定时器","未知的服务ID:%s" % (self.__DeviceFullStatus.delay.services[i].serviceId), QMessageBox.Critical)
            else:
                self.__ui.lineEdit_DelayID.setPlaceholderText("当前设备未配置倒计时")
                self.__ui.lineEdit_DelayID.clear()
                self.__ui.checkBox_DelayEnable.setChecked(False)
                self.__ui.dateTimeEdit_DelayTime.setDateTime(QDateTime.currentDateTime())

            #时区
            self.__ui.comboBox_timezone.blockSignals(True)
            self.__ui.comboBox_timezone.setCurrentText(self.__DeviceFullStatus.timezone)
            self.__ui.comboBox_timezone.blockSignals(False)
            #灯光记忆模式
            self.__ui.comboBox_MemoryLightMode.setCurrentIndex(int(self.__DeviceFullStatus.memoryLightMode))
            #自定义灯光设置
            self.__ui.comboBox_MemoryCustomLightMode.setCurrentIndex(int(self.__DeviceFullStatus.memoryLightAttr.lightMode))
            self.__ui.horizontalSlider_memory_rgbBrightness.setValue(self.__DeviceFullStatus.memoryLightAttr.rgb.rgbBrightness)
            self.__ui.horizontalSlider_memory_Saturation.setValue(self.__DeviceFullStatus.memoryLightAttr.rgb.saturation)
            self.__ui.horizontalSlider_memory_Red.setValue(self.__DeviceFullStatus.memoryLightAttr.rgb.red)
            self.__ui.horizontalSlider_memory_Green.setValue(self.__DeviceFullStatus.memoryLightAttr.rgb.green)
            self.__ui.horizontalSlider_memory_Blue.setValue(self.__DeviceFullStatus.memoryLightAttr.rgb.blue)
            self.__ui.horizontalSlider_memory_whiteBrightness.setValue(self.__DeviceFullStatus.memoryLightAttr.white.whiteBrightness)
            self.__ui.horizontalSlider_memory_Temprature.setValue(self.__DeviceFullStatus.memoryLightAttr.white.temprature)

            #倒计时和定时器日志开关
            self.__ui.checkBox_ScheduleOpenLog.setChecked(self.__DeviceFullStatus.scheduleOpenLog)

            #电流设置
            self.__ui.lineEdit_Current_Blue.setText(str(self.__DeviceFullStatus.currents.blue))
            self.__ui.lineEdit_Current_Red.setText(str(self.__DeviceFullStatus.currents.red))
            self.__ui.lineEdit_Current_Green.setText(str(self.__DeviceFullStatus.currents.green))
            self.__ui.lineEdit_Current_Warm.setText(str(self.__DeviceFullStatus.currents.warm))
            self.__ui.lineEdit_Current_Cold.setText(str(self.__DeviceFullStatus.currents.cold))

    def SetPowerType(self, powerType, messageBox = False):
        powerTypeStr = "未知"
        if powerType == DeviceBulb.PowerType.BULB_TYPE_9W:
            powerTypeStr = "9W"
            self.__ui.label_powerType.setStyleSheet("font:12pt; color:Blue;")
        elif powerType == DeviceBulb.PowerType.BULB_TYPE_12W:
            powerTypeStr = "12W"
            self.__ui.label_powerType.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
        else:
            self.__ui.label_powerType.setStyleSheet("font:12pt; color:Red;")

        self.__ui.label_powerType.setText(powerTypeStr)
        self.__ui.comboBox_powerType.setCurrentText(powerTypeStr)

        if messageBox:
            self.ShowMessageBox("设置设备类型", "设备类型已设置为%s!" % (powerTypeStr))

    def SetLedDriver(self, ledDriver, messageBox = False):
        ledDriverStr = "未知"
        if ledDriver == DeviceBulb.LedDriver.LED_DRIVER_BP5758D:
            ledDriverStr = "BP5758D"
            self.__ui.label_ledDriver.setStyleSheet("font:12pt; color:Blue;")
        elif ledDriver == DeviceBulb.LedDriver.LED_DRIVER_BP1658CJ:
            ledDriverStr = "BP1658CJ"
            self.__ui.label_ledDriver.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
        else:
            self.__ui.label_ledDriver.setStyleSheet("font:12pt; color:Red;")

        self.__ui.label_ledDriver.setText(ledDriverStr)
        self.__ui.comboBox_ledDriver.setCurrentText(ledDriverStr)

        if messageBox:
            self.ShowMessageBox("设置驱动芯片", "设备驱动芯片已设置为%s!" % (ledDriverStr))

    def SetCloudType(self, cloudType, messageBox = False):
        cloudTypeStr = "未知"
        if cloudType == DeviceBulb.CloudType.CHCLOUD_HTTPS_SERVER:
            cloudTypeStr = "国内正式"
            self.__ui.label_cloudType.setStyleSheet("font:12pt; color:Blue;")
        elif cloudType == DeviceBulb.CloudType.CHCLOUD_HTTPS_SERVER_AWS:
            cloudTypeStr = "海外正式"
            self.__ui.label_cloudType.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
        elif cloudType == DeviceBulb.CloudType.CHCLOUD_HTTPS_SERVER_AWS_DEV:
            cloudTypeStr = "海外测试"
            self.__ui.label_cloudType.setStyleSheet("font:12pt; color:Green")
        elif cloudType == DeviceBulb.CloudType.CHCLOUD_HTTPS_SERVER_BUSINESS:
            cloudTypeStr = "商用正式"
            self.__ui.label_cloudType.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
        elif cloudType == DeviceBulb.CloudType.CHCLOUD_HTTPS_SERVER_BUSINESS_DEV:
            cloudTypeStr = "商用测试"
            self.__ui.label_cloudType.setStyleSheet("font:12pt; color:Green")
        elif cloudType == DeviceBulb.CloudType.CHCLOUD_HTTPS_SERVER_LOCAL_TEST:
            cloudTypeStr = "局域网测试"
            self.__ui.label_cloudType.setStyleSheet("font:12pt; color:rgb(150, 100, 0);")
        else:
            self.__ui.label_cloudType.setStyleSheet("font:12pt; color:Red;")

        self.__ui.label_cloudType.setText(cloudTypeStr)
        self.__ui.comboBox_cloudType.setCurrentText(cloudTypeStr)

        if messageBox:
            self.ShowMessageBox("设置云平台", "设备云平台已设置为%s!" % (cloudTypeStr))

    def SetInterfaceType(self, interfaceType, messageBox = False):
        interfaceTypeStr = "未知"
        if interfaceType == DeviceBulb.InterfaceType.INTERFACE_TYPE_E27:
            interfaceTypeStr = "E27"
            self.__ui.label_InterfaceType.setStyleSheet("font:12pt; color:Blue;")
        elif interfaceType == DeviceBulb.InterfaceType.INTERFACE_TYPE_B22:
            interfaceTypeStr = "B22"
            self.__ui.label_InterfaceType.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
        else:
            self.__ui.label_InterfaceType.setStyleSheet("font:12pt; color:Red;")

        self.__ui.label_InterfaceType.setText(interfaceTypeStr)
        self.__ui.comboBox_InterfaceType.setCurrentText(interfaceTypeStr)

        if messageBox:
            self.ShowMessageBox("设置电源接口", "电源接口已设置为%s!" % (interfaceTypeStr))
    
    def SetGradientTime(self, gradientTime, messageBox = False):
        self.__ui.lineEdit_GradientTime.blockSignals(True)
        self.__ui.lineEdit_GradientTime.setText(str(gradientTime));
        self.__ui.lineEdit_GradientTime.blockSignals(False)
        
        if messageBox:
            self.ShowMessageBox("设置渐变时间", "渐变时间已设置为%d!" % (gradientTime))

    def CmdDateReceived(self, data):
        ret, msgName, msgValue = BulbParser.ParseMsg(data)
        if not ret:
            return

        if msgName == "getFullStatus":
            self.SetDeviceFullStatus(msgValue)
            self.ShowMessageBox("设备信息同步", "信息同步成功!")
        elif msgName == "heartbeat":
            self.SetDeviceFullStatus(msgValue)
            self.ShowMessageBox("设备信息同步", "信息同步成功!")
        elif msgName == "rptStatus":
            self.SetDeviceFullStatus(msgValue)
        elif msgName == "setPowerType":
            powerType = msgValue["powerType"]
            self.__DeviceFullStatus.powerType = powerType
            self.SetPowerType(powerType, True)
        elif msgName == "setLedDriver":
            ledDriver = msgValue["ledDriver"]
            self.__DeviceFullStatus.ledDriver = ledDriver
            self.SetLedDriver(ledDriver, True)
        elif msgName == "setCloudType":
            cloudType = msgValue["cloudType"]
            self.__DeviceFullStatus.cloudType = cloudType
            self.SetCloudType(cloudType, True)
        elif msgName == "setInterfaceType":
            interfaceType = msgValue["interfaceType"]
            self.__DeviceFullStatus.interfaceType = interfaceType
            self.SetInterfaceType(interfaceType, True)
        elif msgName == "setGradientTime":
            gradientTime = msgValue["gradientTime"]
            self.__DeviceFullStatus.gradientTime = gradientTime
            self.SetGradientTime(gradientTime, True)
        elif msgName == "setWiFi":
            ret = msgValue["ret"]
            self.ShowMessageBox("设置Wi-Fi", "Wi-Fi信息设置%s!" % ("成功" if ret != 0 else "失败"), QMessageBox.Information if ret != 0 else QMessageBox.Critical)
        elif msgName == "setSchedule":
            openLog = msgValue["openLog"]
            self.__DeviceFullStatus.scheduleOpenLog = openLog
            self.ShowMessageBox("设置倒计时和定时器日志开关", "倒计时和定时器日志开关已经%s!" % ("开启" if openLog != 0 else "关闭"))
        elif msgName == "setCurrent":
            self.SetDeviceFullStatus(msgValue)
            self.ShowMessageBox("设置电流", "设置电流完成!")
        elif msgName == "otaProcess":
            if self._OtaStarted:
                otaProcess = DeviceBulb.OtaProcess()
                BulbParser.ParseOtaProcess(msgValue, otaProcess)
                if len(otaProcess.startTime) > 0 and len(otaProcess.totalTime) > 0:
                    startTime = otaProcess.startTime.toLongLong()
                    startDateTime = QDateTime.fromMSecsSinceEpoch(startTime).toString("yyyy-MM-dd HH:mm:ss")
                    self._OtaStarted = False
                    self.ShowMessageBox("设备升级", "设备升级开始\r\n开始时间\"%s\",预计用时%2秒!" % (startDateTime, otaProcess.totalTime))
                else:
                    if otaProcess.progress.isdigit():
                        progress = int(otaProcess.progress)
                        self.__ui.progressBar_Ota.setVisible(100 != progress)
                        self.__ui.progressBar_Ota.setValue(progress)

                    if otaProcess.process.isdigit():
                        process = int(otaProcess.process)
                        if 1 == process:
                            self._OtaStarted = False
                            self.ShowMessageBox("设备升级", "设备下载完成,等待安装...")
        elif msgName == "otaResult":
            self.__ui.progressBar_Ota.setVisible(False)
            otaResult = DeviceBulb.OtaResult()
            BulbParser.ParseOtaResult(msgValue, otaResult)
            if "0" == otaResult.result:
                self.ShowMessageBox("设备升级", "设备升级失败!", QMessageBox.Icon.Critical)
            else:
                self.ShowMessageBox("设备升级", "设备升级成功!")

    @Slot()
    def on_checkBox_switch_clicked(self):
        cmd = BulbParser.PackSetSwitch(self.__ui.checkBox_switch.isChecked())
        self.SendCommandText(cmd)
        
    @Slot()
    def on_checkBox_noDisturb_clicked(self):
        cmd = BulbParser.PackSetNoDisturb(self.__ui.checkBox_noDisturb.isChecked())
        self.SendCommandText(cmd)
        
    @Slot()
    def on_pushButton_Sync_clicked(self):
        cmd = BulbParser.PackGetFullStatus()
        self.SendCommandText(cmd)
        
    @Slot(int)
    def on_horizontalSlider_rgbBrightness_valueChanged(self, value):
        cmd = BulbParser.PackSetLight("rgbBrightness", "brightness", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Saturation_valueChanged(self, value):
        cmd = BulbParser.PackSetLight("saturation", "ratio", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Red_valueChanged(self, value):
        cmd = BulbParser.PackSetLight("colour", "red", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Green_valueChanged(self, value):
        cmd = BulbParser.PackSetLight("colour", "green", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Blue_valueChanged(self, value):
        cmd = BulbParser.PackSetLight("colour", "blue", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_whiteBrightness_valueChanged(self, value):
        cmd = BulbParser.PackSetLight("whiteBrightness", "brightness", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Temprature_valueChanged(self, value):
        cmd = BulbParser.PackSetLight("colorTemperature", "ratio", value)
        self.SendCommandText(cmd)
                
    @Slot()
    def on_pushButton_SetRGB_clicked(self):
        rgb = DeviceBulb.RGB(int(self.__ui.horizontalSlider_rgbBrightness.value()), self.__ui.horizontalSlider_Saturation.value(), int(self.__ui.horizontalSlider_Red.value()), int(self.__ui.horizontalSlider_Green.value()), int(self.__ui.horizontalSlider_Blue.value()))
        cmd = BulbParser.PackSetRGB(rgb)
        self.SendCommandText(cmd)

        self.__ui.label_CurrLightMode.setText(("彩光"))
        self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:rgb(255, 0, 255);")
                        
    @Slot()
    def on_pushButton_SetWhite_clicked(self):
        white = DeviceBulb.White(int(self.__ui.horizontalSlider_whiteBrightness.value()), int(self.__ui.horizontalSlider_Temprature.value()))
        cmd = BulbParser.PackSetWhite(white)
        self.SendCommandText(cmd)

        self.__ui.label_CurrLightMode.setText(("白光"))
        self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:black;")
               
    @Slot()
    def on_pushButton_SetAtmosphere_clicked(self):
        cmd = BulbParser.PackSetAtmosphere(self.__ui.lineEdit_AtmosphereID.text(), self.__ui.plainTextEdit_AtmosphereScript.toPlainText())
        self.SendCommandText(cmd)

        self.__ui.label_CurrLightMode.setText(("氛围"))
        self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")

    @Slot()
    def on_pushButton_SetAtmosphereSend_clicked(self):
        cmd = BulbParser.PackSetAtmosphereSend(self.__ui.lineEdit_AtmosphereID.text(), self.__ui.plainTextEdit_AtmosphereScript.toPlainText())
        self.SendCommandText(cmd)

    @Slot()
    def on_pushButton_AddTimer_clicked(self):
        if QDialog.Accepted == self.__TimerSetWindow.exec():
            timer = self.__TimerSetWindow.GetTimer()
            self.SetTimerToList(timer, True)
                            
    @Slot()
    def on_pushButton_DelTimer_clicked(self):
        rowCount = self.__ui.tableWidget_Timers.currentRow()
        if rowCount >= 0:
            self.__ui.tableWidget_Timers.removeRow(rowCount)

            timer = DeviceBulb.Timer()
            timer.id = self.__Timers[rowCount].id
            timer.week = 0

            del self.__Timers[rowCount]

            cmd = BulbParser.PackSetTimer(timer)
            self.SendCommandText(cmd)
                            
    @Slot(QTableWidgetItem)
    def on_tableWidget_Timers_itemDoubleClicked(self, item):
        rowCount = item.row()
        timer = self.__Timers[rowCount]
        self.__TimerSetWindow.SetTimer(timer)
        if QDialog.Accepted == self.__TimerSetWindow.exec():
            timer = self.__TimerSetWindow.GetTimer()
            self.SetTimerToList(timer, True)
                                        
    @Slot(int)
    def on_checkBox_DelaySwitch_stateChanged(self, state):
        self.__ui.comboBox_DelayLightMode.setEnabled(state == Qt.Checked.value)
        self.__ui.groupBox_DelayRGB.setEnabled(self.__ui.comboBox_DelayLightMode.currentIndex() == 0 and state == Qt.Checked.value)
        self.__ui.groupBox_DelayWhite.setEnabled(self.__ui.comboBox_DelayLightMode.currentIndex() == 1 and state == Qt.Checked.value)
                            
    @Slot(int)
    def on_comboBox_DelayLightMode_currentIndexChanged(self, index):
        self.__ui.groupBox_DelayRGB.setEnabled(self.__ui.checkBox_DelaySwitch.isChecked() and 0 == index)
        self.__ui.groupBox_DelayWhite.setEnabled(self.__ui.checkBox_DelaySwitch.isChecked() and 1 == index)
                                    
    @Slot()
    def on_pushButton_Delay_clicked(self):
        delay = DeviceBulb.Delay()
        #定时器ID
        delay.id = self.__ui.lineEdit_DelayID.text().strip()
        #定时器启用
        delay.enable = self.__ui.checkBox_DelayEnable.isChecked()
        #开始时间
        delay.start = 0
        #结束时间
        delay.end = self.__ui.dateTimeEdit_DelayTime.dateTime().toSecsSinceEpoch()

        services = []
        #灯开关
        switch_on = DeviceBulb.ServiceParams("switch", "on", self.__ui.checkBox_DelaySwitch.isChecked())
        services.append(switch_on)
        if self.__ui.checkBox_DelaySwitch.isChecked():
            #灯光模式
            lightmode = DeviceBulb.ServiceParams("lightMode", "status", self.__ui.comboBox_DelayLightMode.currentIndex())
            services.append(lightmode)
            #服务配置项
            if DeviceBulb.LightMode.LIGHT_RGB == lightmode.paraValue:
                services.append(DeviceBulb.ServiceParams("rgbBrightness", "brightness", self.__ui.horizontalSlider_Delay_rgbBrightness.value()))
                services.append(DeviceBulb.ServiceParams("saturation", "ratio", self.__ui.horizontalSlider_Delay_Saturation.value()))
                services.append(DeviceBulb.ServiceParams("colour", "red", self.__ui.horizontalSlider_Delay_Red.value()))
                services.append(DeviceBulb.ServiceParams("colour", "green", self.__ui.horizontalSlider_Delay_Green.value()))
                services.append(DeviceBulb.ServiceParams("colour", "blue", self.__ui.horizontalSlider_Delay_Blue.value()))
            else:
                services.append(DeviceBulb.ServiceParams("whiteBrightness", "brightness", self.__ui.horizontalSlider_Delay_whiteBrightness.value()))
                services.append(DeviceBulb.ServiceParams("colorTemperature", "ratio", self.__ui.horizontalSlider_Delay_Temprature.value()))
        delay.services = services

        cmd = BulbParser.PackSetDelay(delay)
        self.SendCommandText(cmd)
                                    
    @Slot()
    def on_pushButton_DelayDelete_clicked(self):
        delay = DeviceBulb.Delay()
        delay.end = 0

        cmd = BulbParser.PackSetDelay(delay)
        self.SendCommandText(cmd)
                                    
    @Slot(int)
    def on_comboBox_MemoryCustomLightMode_currentIndexChanged(self, index):
        self.__ui.groupBox_MemoryRGB.setEnabled(0 == index)
        self.__ui.groupBox_MemoryWhite.setEnabled(1 == index)
                                    
    @Slot(str)
    def on_comboBox_timezone_currentTextChanged(self, text):
        cmd = BulbParser.PackSetTimezone(text.strip())
        self.SendCommandText(cmd)
                            
    @Slot(int)
    def on_comboBox_MemoryLightMode_currentIndexChanged(self, index):
        self.__ui.groupBox_CustomMemoryLight.setEnabled(int(DeviceBulb.MemoryLightMode.MEMORY_LIGHT_CUSTOM) == index)
                                    
    @Slot(int)
    def on_comboBox_MemoryLightMode_activated(self, index):
        cmd = BulbParser.PackSetMemoryLightMode(index)
        self.SendCommandText(cmd)
                                    
    @Slot()
    def on_pushButton_MemoryLight_clicked(self):
        #灯光模式
        services = []
        lightmode = DeviceBulb.ServiceParams("lightMode", "status", self.__ui.comboBox_MemoryCustomLightMode.currentIndex())
        services.append(lightmode)
        #服务配置项
        if DeviceBulb.LightMode.LIGHT_RGB == lightmode.paraValue:
            services.append(DeviceBulb.ServiceParams("rgbBrightness", "brightness", self.__ui.horizontalSlider_memory_rgbBrightness.value()))
            services.append(DeviceBulb.ServiceParams("saturation", "ratio", self.__ui.horizontalSlider_memory_Saturation.value()))
            services.append(DeviceBulb.ServiceParams("colour", "red", self.__ui.horizontalSlider_memory_Red.value()))
            services.append(DeviceBulb.ServiceParams("colour", "green", self.__ui.horizontalSlider_memory_Green.value()))
            services.append(DeviceBulb.ServiceParams("colour", "blue", self.__ui.horizontalSlider_memory_Blue.value()))
        else:
            services.append(DeviceBulb.ServiceParams("whiteBrightness", "brightness", self.__ui.horizontalSlider_memory_whiteBrightness.value()))
            services.append(DeviceBulb.ServiceParams("colorTemperature", "ratio", self.__ui.horizontalSlider_memory_Temprature.value()))

        cmd = BulbParser.PackSetMemoryLightAttr(services)
        self.SendCommandText(cmd)
                                    
    @Slot()
    def on_pushButton_unbind_clicked(self):
        cmd = BulbParser.PackUnbind()
        self.SendCommandText(cmd)
                                    
    @Slot()
    def on_checkBox_ScheduleOpenLog_clicked(self):
        cmd = BulbParser.PackSetScheduleOpenLog(self.__ui.checkBox_ScheduleOpenLog.isChecked())
        self.SendCommandText(cmd)

    @Slot(int)
    def on_comboBox_powerType_activated(self, index):
        cmd = BulbParser.PackSetPowerType(index)
        self.SendCommandText(cmd)
                                    
    @Slot(int)
    def on_comboBox_ledDriver_activated(self, index):
        cmd = BulbParser.PackSetLedDriver(index)
        self.SendCommandText(cmd)

    @Slot(int)
    def on_comboBox_cloudType_activated(self, index):
        cmd = BulbParser.PackSetCloudType(index + 1)
        self.SendCommandText(cmd)

    @Slot(int)
    def on_comboBox_InterfaceType_activated(self, index):
        cmd = BulbParser.PackSetInterfaceType(index)
        self.SendCommandText(cmd)
        
    @Slot(str)
    def on_lineEdit_GradientTime_textChanged(self, text):
        cmd = BulbParser.PackSetGradientTime(text)
        self.SendCommandText(cmd)
                                    
    @Slot()
    def on_pushButton_SendWiFi_clicked(self):
        cmd = BulbParser.PackSetWiFi(self.__ui.lineEdit_SSID.text(), self.__ui.lineEdit_Password.text())
        self.SendCommandText(cmd)
                                    
    @Slot()
    def on_pushButton_upgrade_clicked(self):
        cmd = BulbParser.PackUpgrade(self.__ui.lineEdit_upgradePackageId.text(), self.__ui.lineEdit_downloadUrl.text(), self.__ui.label_Mac.text(), self.__ui.lineEdit_newVersion.text(), self.__ui.lineEdit_md5.text(), self.__ui.lineEdit_size.text())
        self.SendCommandText(cmd)
        self._OtaStarted = True
                                    
    @Slot()
    def on_pushButton_SetCurrent_clicked(self):
        cmd = BulbParser.PackSetCurrent(int(self.__ui.lineEdit_Current_Red.text()), int(self.__ui.lineEdit_Current_Green.text()), int(self.__ui.lineEdit_Current_Blue.text()), int(self.__ui.lineEdit_Current_Warm.text()), int(self.__ui.lineEdit_Current_Cold.text()))
        self.SendCommandText(cmd)

    def SetTimerToList(self, timer, send = False):
        rowCount = -1
        i = 0
        while i < self.__ui.tableWidget_Timers.rowCount():
            txt = self.__ui.tableWidget_Timers.item(i, 0).text()
            if timer.id == txt:
                rowCount = i
                break
            i += 1

        if rowCount < 0:
            rowCount = self.__ui.tableWidget_Timers.rowCount()
            self.__ui.tableWidget_Timers.insertRow(rowCount)

            self.__Timers.append(timer)
        else:
            self.__Timers[rowCount] = timer

        self.__ui.tableWidget_Timers.setItem(rowCount, 0, QTableWidgetItem(timer.id))

        item = QTableWidgetItem(("启用" if timer.enable else "未启用"))
        item.setForeground(QColor.fromRgb(0, 170, 0) if timer.enable else Qt.red)

        self.__ui.tableWidget_Timers.setItem(rowCount, 1, item)
        self.__ui.tableWidget_Timers.setItem(rowCount, 2, QTableWidgetItem(timer.start))
        self.__ui.tableWidget_Timers.setItem(rowCount, 3, QTableWidgetItem(timer.end))
        self.__ui.tableWidget_Timers.setItem(rowCount, 4, QTableWidgetItem(timer.GetWeekString()))

        if send:
            cmd = BulbParser.PackSetTimer(timer)
            self.SendCommandText(cmd)

    def HttpStarted(self):
        self.__ui.lineEdit_downloadUrl.setText(self._OtaUrl % (self._HttpServerWindow.GetIP(), self._HttpServerWindow.GetPort(), self._SupportDevice.deviceBinName))

    def HttpStopped(self):
        pass

